package com.hunantv.mglive.ui.discovery.publisher.pic;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.utils.L;
import com.hunantv.mglive.utils.Toast;

/**
 * @author maxxiang
 *
 *提供一些通用的函数
 */



public class Utils {
	private static String TAG = Utils.class.getSimpleName();
	
	private static int mWidth = 0;		//用于保存屏幕宽
	private static int mHeight = 0;
	private static float mDensity = 0.f;
	
    public static int getScreenWidth(){
    	if (mWidth == 0){
    		mWidth = MaxApplication.getApp().getAppContext().getResources().getDisplayMetrics().widthPixels;
    	}
        return mWidth;        
    }

    public static int getScreenHeight(){
    	if (mHeight == 0){
    		mHeight = MaxApplication.getApp().getAppContext().getResources().getDisplayMetrics().heightPixels;
    	}
        return mHeight;                 
    }
    
	public static float getScreenDensity() {
		if (mDensity == 0.f) {
			mDensity = MaxApplication.getApp().getAppContext().getResources().getDisplayMetrics().density;
		}
		return mDensity;
	}
    
    public static int getStatusBarHeight(){
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        
        Context context = MaxApplication.getApp().getAppContext();
        
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        } 
        return statusBarHeight;
    }
    
	public static String formatDigit(int iNum) {
		
		if (iNum < 10000) {
			return String.valueOf(iNum);
		}

		DecimalFormat sdf = null;
		if (iNum % 10000 < 1000){
			sdf = new DecimalFormat("##万+");
		}
		else{
			sdf = new DecimalFormat("##.#万");
		}
		
		double f = iNum * 1.0f / 10000.0;
		String str = sdf.format(f);
		return str;

	}
    
    //is横屏
    public static boolean isLandscape()
    {
        final int screenWidth = getScreenWidth();
        final int screenHeight = getScreenHeight();
        return screenWidth > screenHeight;
    }
    
    /**
	 * 根据一个网络连接(String)获取bitmap图像
	 * 
	 * @param imageUri
	 * @return
	 * @throws MalformedURLException
	 */
	public static Bitmap getbitmap(String imageUri) {
		Log.v(TAG, "getbitmap:" + imageUri);
		// 显示网络上的图片
		Bitmap bitmap = null;
		try {
			URL myFileUrl = new URL(imageUri);
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();

			Log.v(TAG, "image download finished." + imageUri);
		} catch (IOException e) {
			e.printStackTrace();
			Log.v(TAG, "getbitmap bmp fail---");
			return null;
		}
		return bitmap;
	}
	
	public static String getSimpleTime(long publicsTime) {

		String simpleTime = null;
		long now = System.currentTimeMillis()*1000;
		long deltime = (now - publicsTime)/1000000;//second

		if (deltime >= 365 * 24 * 60 * 60) {
			Timestamp timeStamp = new Timestamp(publicsTime / 1000);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月dd日");
			simpleTime = sdf.format(timeStamp);
			
		} else if (deltime >= 2 * 24 * 60 * 60) {
			Timestamp timeStamp = new Timestamp(publicsTime / 1000);
			SimpleDateFormat sdf = new SimpleDateFormat("M月dd日");
			simpleTime = sdf.format(timeStamp);
			
		} else if (deltime > 24 * 60 * 60) {
			
			simpleTime = "昨天";
			
		} else if (deltime > 60 * 60) {
			
			simpleTime = (int) (deltime / (60 * 60)) + "小时前";
			
		} else if (deltime > 60) {
			
			simpleTime = (int) (deltime / (60)) + "分钟前";
			
		} else  {
			
			simpleTime = "刚刚";
		}

		return simpleTime;
	}
	
	//获取当前时间，微秒
	public static long getCurrentTimeInMicroseconds(){
		return System.currentTimeMillis()*1000;
	}
	public static String getTwoDaysSimpleTime(long publicsTime) {

		String simpleTime = null;
		long now = Calendar.getInstance().getTimeInMillis();
		long deltime = now / 1000 - publicsTime;

		if (deltime >= 2 * 24 * 60 * 60) 
		{
			Timestamp timeStamp = new Timestamp(publicsTime * 1000);
			SimpleDateFormat sdf = new SimpleDateFormat("dd/yyyy/MM");
			simpleTime = sdf.format(timeStamp);
		} 
		else if (deltime > 24 * 60 * 60) 
		{
			simpleTime = "昨天";
		} 
		else 
		{
			simpleTime = "今天";
		}

		return simpleTime;
	}
	
	public static boolean isNull(final String obj){
		if((obj==null) || (obj.length()<1)){
			return true;
		}
		return false;
	}
	
	public static boolean fileExists(String filePath){
		if(isNull(filePath)){
			return false;
		}
		File file = new File(filePath);
		if(file.exists())
			return true;
		
		return false;
	}
	
	
	public static <T extends java.io.Serializable> String serialObject(T obj) {
		if (obj != null) {
			ObjectOutputStream OOS = null;
			ByteArrayOutputStream BAOS = new ByteArrayOutputStream();
			try {
				OOS = new ObjectOutputStream(BAOS);
				OOS.writeObject(obj);
				String serStr = BAOS.toString("ISO-8859-1");
				OOS.close();
				BAOS.close();
				return serStr;
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception ex) {
				ex.printStackTrace();
			}

		}
		return null;
	}
	
	public static <T extends java.io.Serializable> T deseriaObject(String src) {
		if (src != null && src.length() > 0) {
			ByteArrayInputStream BAIS = null;
			ObjectInputStream OIS = null;
			try {
				BAIS = new ByteArrayInputStream(src.getBytes("ISO-8859-1"));
				OIS = new ObjectInputStream(BAIS);

				T it = (T) (OIS.readObject());
				OIS.close();
				BAIS.close();
				return it;
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception ex) {
				ex.printStackTrace();
			}

		}
		return null;
	}
    
	public static String getTakePhotoPath() {

		File f = new File(PublisherConstants.PHOTO_DIR_Path);
		if (!f.exists()) {
			f.mkdirs();
		}
		String photoPath = PublisherConstants.PHOTO_DIR_Path + getPhotoFileName();
		return photoPath;
	}

	public static String getPhotoFileName() {
		Date date = new java.util.Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'yyyyMMdd_HHmmss");
		return dateFormat.format(date) + ".jpg";
	}


	public static void doTakePhoto(Activity activity, String photoFileName) {
		if (activity == null || photoFileName == null || photoFileName.length() <= 0)
			return;

		try { // Launch camera to take photo for selected contact
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
			Uri uploadPhotoUri = Uri.fromFile(new File(photoFileName));
			intent.putExtra(MediaStore.EXTRA_OUTPUT, uploadPhotoUri);
			intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 100);
			activity.startActivityForResult(intent, PublisherConstants.REQ_CAMERA_DATA);
		} catch (Exception e) {
			Toast.makeText(activity, "调用拍照失败!", Toast.LENGTH_SHORT).show();
		}
	}
	
	public static final String	URL_CODING							= "utf-8";
	public static String urlEncode(String str)
	{
		if (TextUtils.isEmpty(str))
			return null;

		String result = str;
		try
		{
			result = URLEncoder.encode(str, URL_CODING);
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		catch (Exception e)
		{
			L.e(TAG, "encode url failure");
		}
		return result;
	}
}
